import { getPageStaticApi } from "@/api/client/documentManagement/waybillManagement";
import { getListApi } from "@/api/client/documentManagement/waybillManagement";
import { printLabelApi } from "@/api/common";
import CommonHook from "@/hook/commonHook";
import { message } from "ant-design-vue";
import dayjs from "dayjs";
import printJs from "print-js";
import { computed } from "vue";
import { message as Message } from "ant-design-vue";
import { cancelMergeDeclarationApi, customerShipmentCostExcelApi, customerShipmentExcelApi, customsClearanceApi, shipmentBoxVolumeExcelListApi } from "@/api/waybillManagement/customerServiceWaybill";
export default function OperationHook(state: Base.GeneraDataType) {
  const { searchForm, tableData, drawerOpts, loading, activeKey, pageStat, tableRef } = state;
  const selectRows = computed<Array<ClientWaybillManagement.ListRows>>(() => {
    return tableRef.value.xTable.getCheckboxRecords() || [];
  });
  const { getNoZeroKey, downloadFileByBlob, downloadFileByUrl } = CommonHook();
  const getData = async () => {
    const params = {
      ...getParams(),
      selectStatus: Number(activeKey.value)
    };
    loading.value = true;
    tableData.value = [];
    return getListApi(params)
      .then((res: any) => {
        const { code, data } = res;
        if (code === 200) {
          tableData.value = data.records || [];
          searchForm.total = Number(data.total);
        }
      })
      .finally(() => {
        loading.value = false;
      });
  };
  const pageStateic = () => {
    const params = getParams();
    return getPageStaticApi(params).then((res: any) => {
      const { code, data } = res;
      if (code === 200) {
        Object.assign(pageStat.value, data);
        activeKey.value = String(getNoZeroKey(pageStat.value, ["-1", "1", "5", "8", "9", "0", "-2"]));
      }
    });
  };
  const getParams = () => {
    const { waybillNumList, countryRegionName, createdTime, channelId, warehouseCode, remark, pageNum, pageSize, fbaNumberList, transferOrderNumberList } = searchForm;
    const params: any = {
      waybillNumList: [],
      countryRegionName,
      channelId: channelId?.length ? channelId[2] : "",
      warehouseCode,
      remark,
      startTime: createdTime.length ? dayjs(createdTime[0]).startOf("day").format("YYYY-MM-DD HH:mm:ss") : undefined,
      endTime: createdTime.length ? dayjs(createdTime[1]).endOf("day").format("YYYY-MM-DD HH:mm:ss") : undefined,
      pageNum,
      pageSize
    };
    if (waybillNumList)
      params.waybillNumList = waybillNumList
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");
    if (fbaNumberList)
      params.fbaNumberList = fbaNumberList
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");
    if (transferOrderNumberList)
      params.transferOrderNumberList = transferOrderNumberList
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");

    return params;
  };
  const searchHandle = async () => {
    searchForm.pageNum = 1;
    await pageStateic();
    getData();
  };
  const changeTabHandle = () => {
    getData();
  };
  const editHandle = (row: ClientWaybillManagement.ListRows) => {
    drawerOpts.title = `编辑(${row.preOrderNo})`;
    drawerOpts.width = "1200px";
    drawerOpts.type = 2;
    drawerOpts.component = "Details";
    drawerOpts.passData = row;
    drawerOpts.visible = true;
  };
  const showHandle = (row: ClientWaybillManagement.ListRows) => {
    drawerOpts.title = `查看(${row.waybillNum})`;
    drawerOpts.width = "1200px";
    drawerOpts.type = 1;
    drawerOpts.component = "Details";
    drawerOpts.passData = row;
    drawerOpts.visible = true;
  };
  const cancelHandle = (row: ClientWaybillManagement.ListRows) => {
    drawerOpts.title = `取消预报(${row.waybillNum})`;
    drawerOpts.width = "1200px";
    drawerOpts.type = 1;
    drawerOpts.component = "CancelAdvance";
    drawerOpts.passData = row;
    drawerOpts.visible = true;
  };
  const makeInvoiceHandle = () => {
    if (!selectRows.value.length) return message.error("请勾选运单!");
    if (selectRows.value.length > 1) return message.error("只能勾选一条运单!");

    if (selectRows.value) drawerOpts.title = `制作发票`;
    drawerOpts.width = "1200px";
    drawerOpts.type = 1;
    drawerOpts.component = "MakeInvoice";
    drawerOpts.passData = selectRows.value[0];
    drawerOpts.visible = true;
  };
  // 打印
  const printLabelHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    loading.value = true;
    printLabelApi({ idList: selectRows.value.map((t: ClientAdvanceManagement.ListRows) => t.id), type: 2 })
      .then((res: any) => {
        if (res.headers["content-type"] === "application/json") {
          const reader = new FileReader(); //创建一个FileReader实例
          reader.readAsText(res.data, "utf-8"); //读取文件,结果用字符串形式表示
          reader.onload = () => {
            //读取完成后,**获取reader.result**
            const { message } = JSON.parse(reader.result as string);
            Message.error(message); //弹出错误提示
          };
        } else {
          const pdfUrl = window.URL.createObjectURL(res.data);
          printJs({ printable: pdfUrl, type: "pdf" });
        }
      })
      .finally(() => (loading.value = false));
  };
  // 下载标签
  const downloadLabelHandle = (buttonType: number | undefined) => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    loading.value = true;
    printLabelApi({ idList: selectRows.value.map((t: ClientAdvanceManagement.ListRows) => t.id), type: 2, buttonType })
      .then((res: any) => {
        if (res.headers["content-type"] === "application/json") {
          const reader = new FileReader(); //创建一个FileReader实例
          reader.readAsText(res.data, "utf-8"); //读取文件,结果用字符串形式表示
          reader.onload = () => {
            //读取完成后,**获取reader.result**
            const { message } = JSON.parse(reader.result as string);
            Message.error(message); //弹出错误提示
          };
        } else {
          //判断推单状态
          if (res.headers["content-type"] === "application/pdf") {
            const { waybillNum, channelName, itemNumber } = selectRows.value[0];
            downloadFileByBlob(res.data, `${waybillNum}+${itemNumber}件+${channelName}.pdf`, "application/pdf");
          } else {
            downloadFileByBlob(res.data, "标签.zip");
          }
        }
      })
      .finally(() => (loading.value = false));
  };

  //材积明细导出
  const VolumeExportHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    loading.value = true;
    return shipmentBoxVolumeExcelListApi(selectRows.value.map((t: any) => t.id))
      .then((res: any) => {
        const { filename } = res.headers;
        const name = filename.split(".");
        name && name.length && downloadFileByBlob(res.data, `材积明细.${name[1]}`);
      })
      .finally(() => {
        loading.value = false;
      });
  };
  const getPopupContainer = () => document.querySelector(".nav-header-page");

  //合并报关
  const customsClearanceHandle = () => {
    if (selectRows.value.length < 2) return Message.error("至少勾选两条运单!");
    loading.value = true;
    return customsClearanceApi(selectRows.value.map((t: any) => t.id))
      .then((res: any) => {
        const { code } = res;
        if (code === 200) {
          Message.success("操作成功!");
          searchHandle();
        }
      })
      .finally(() => {
        loading.value = false;
      });
  };

  //取消合并报关
  const cancelMergeDeclarationHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    loading.value = true;
    return cancelMergeDeclarationApi(selectRows.value.map((t: any) => t.id))
      .then((res: any) => {
        const { code } = res;
        if (code === 200) {
          Message.success("操作成功!");
          searchHandle();
        }
      })
      .finally(() => {
        loading.value = false;
      });
  };
  //费用导出
  const exportPriceHandle = () => {
    const params = {
      ...getParams(),
      idList: selectRows.value.length ? selectRows.value.map((t: any) => t.id) : undefined,
      selectStatus: Number(activeKey.value)
    };

    return customerShipmentCostExcelApi(params).then((res: any) => {
      const { data } = res;
      downloadFileByUrl(data, "运单费用明细.xlsx");
    });
  };
  //客户端-导出运单
  const exportWaybillHandle = () => {
    const params = {
      ...getParams(),
      idList: selectRows.value.length ? selectRows.value.map((t: any) => t.id) : undefined,
      selectStatus: Number(activeKey.value)
    };
    return customerShipmentExcelApi(params).then((res: any) => {
      downloadFileByBlob(res.data, `运单导出.xlsx`);
    });
  };

  //合并下载标签
  const batchDownLoadHandle = () => {
    console.log(123);
  };

  return {
    searchHandle,
    getData,
    editHandle,
    showHandle,
    changeTabHandle,
    cancelHandle,
    pageStateic,
    makeInvoiceHandle,
    printLabelHandle,
    downloadLabelHandle,
    VolumeExportHandle,
    getPopupContainer,
    customsClearanceHandle,
    cancelMergeDeclarationHandle,
    exportPriceHandle,
    exportWaybillHandle,
    batchDownLoadHandle
  };
}
